﻿using System;
using System.Linq;
using Icinetic.FeedCategorySample.Common.Base;
using Icinetic.FeedCategorySample.ViewModel;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace Icinetic.FeedCategorySample
{
    public sealed partial class SearchResultsPage : LayoutAwarePage
    {
        private UIElement _previousContent;

        public SearchResultsPage()
        {
            this.InitializeComponent();
        }

        public static void Activate(String queryText)
        {
            // If the Window isn't already using Frame navigation, insert our own Frame
            var previousContent = Window.Current.Content;
            var frame = previousContent as Frame;
            if (frame == null)
            {
                frame = new Frame();
                Window.Current.Content = frame;
            }

            // Use navigation to display the results, packing both the query text and the previous
            // Window content into a single parameter object
            frame.Navigate(typeof(SearchResultsPage),
                new Tuple<String, UIElement>(queryText, previousContent));
            Window.Current.Activate();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The
        /// Parameter property provides the collection of items to be displayed.</param>
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            // Unpack the two values passed in the parameter object: query text and previous
            // Window content
            var parameter = (Tuple<String, UIElement>)e.Parameter;
            var queryText = parameter.Item1;
            this._previousContent = parameter.Item2;

            SearchResultsViewModel model = new SearchResultsViewModel(queryText, _previousContent);
            this.DataContext = model;
            await model.Load(queryText);
        }

        /// <summary>
        /// Invoked when the back button is pressed.
        /// </summary>
        /// <param name="sender">The Button instance representing the back button.</param>
        /// <param name="e">Event data describing how the button was clicked.</param>
        protected override void GoBack(object sender, RoutedEventArgs e)
        {
            // Return the application to the state it was in before search results were requested
            var frame = this._previousContent as Frame;
            if (frame != null)
            {
                frame.GoBack();
            }
            else
            {
                Window.Current.Content = this._previousContent;
            }
        }

        /// <summary>
        /// Invoked when a filter is selected using the ComboBox in snapped view state.
        /// </summary>
        /// <param name="sender">The ComboBox instance.</param>
        /// <param name="e">Event data describing how the selected filter was changed.</param>
        void Filter_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // Determine what filter was selected
            var selectedFilter = e.AddedItems.FirstOrDefault() as Filter;
            if (selectedFilter != null)
            {
                // Mirror the results into the corresponding Filter object to allow the
                // RadioButton representation used when not snapped to reflect the change
                selectedFilter.Active = true;

                // TODO: Respond to the change in active filter by setting this.DefaultViewModel["Results"]
                //       to a collection of items with bindable Image, Title, and Subtitle properties
                (this.DataContext as SearchResultsViewModel).SelectedFilter = selectedFilter;
            }
        }

        /// <summary>
        /// Invoked when a filter is selected using a RadioButton when not snapped.
        /// </summary>
        /// <param name="sender">The selected RadioButton instance.</param>
        /// <param name="e">Event data describing how the RadioButton was selected.</param>
        void Filter_Checked(object sender, RoutedEventArgs e)
        {
            // Mirror the change into the CollectionViewSource used by the corresponding ComboBox
            // to ensure that the change is reflected when snapped
            if (filtersViewSource.View != null)
            {
                var filter = (sender as FrameworkElement).DataContext;
                filtersViewSource.View.MoveCurrentTo(filter);
            }
        }

        /// <summary>
        /// Invoked when a result item is clicked.
        /// </summary>
        /// <param name="sender">The clicked item instance.</param>
        /// <param name="e">Event data describing how the item was clicked.</param>
        private void OnItemClick(object sender, ItemClickEventArgs e)
        {
            SearchResultItem item = e.ClickedItem as SearchResultItem;
            // Navigate to the page showing the recipe that was clicked
            this.Frame.Navigate(item.ViewType, (e.ClickedItem as SearchResultItem).EntityInstance);
        }
    }
}
